package com.echo.boot.controller;

public class Partition {
    public static void main(String[] args) {
        Object partitionCol = "35808879";// 分库键
        Integer tableCount = 64;// 单库表数
        Integer dbCount = 2;// 库数
        getPartitionCol(partitionCol, tableCount, dbCount);
    }

    private static void getPartitionCol(Object partitionCol, Integer tableCount, Integer dbCount) {
        if (dbCount < 2) {
            int tableIndex = getPartitionIdByPartitionValue(partitionCol, tableCount) - 1;
            System.out.println("数据应在：" + tableIndex + "号表");
        } else {
            int tb = getPartitionIdByPartitionValue(partitionCol, tableCount * dbCount) - 1;
            int dbIndex = tb % dbCount;
            int tableIndex = tb / dbCount;
            System.out.println("分库键:" + partitionCol + "," + dbIndex + "号库," + tableIndex + "号表");
        }
    }

    private static int getPartitionIdByPartitionValue(Object partitionValue, int hashSize) {
        int hashCode = Math.abs(partitionValue.hashCode());
        return Math.abs((hashCode - 1)) % hashSize + 1;
    }
}
